package com.company.linkedList;

import java.util.List;

public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode nthNode=null;
        ListNode cursorNode=head;
        ListNode nthPreNode=null;

        int count = n;
        while (cursorNode!=null){
            cursorNode = cursorNode.next;
            if (count>1) {
                count--;
                continue;
            }
            if (nthNode == null) {
                nthNode = head;
            }else {
                nthPreNode = nthNode;
                nthNode = nthNode.next;
            }
        }

        if (nthNode == head) {
            head = head.next;
            nthNode.next = null;
        }else {
            nthPreNode.next = nthNode.next;
        }
        return head;
    }
}
